<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/murmur/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/murmur/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/murmur/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/murmur/images/logo.svg" color="#222">

<link rel="stylesheet" href="/murmur/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css">
  <script src="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js"></script>

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/murmur/","scheme":"Gemini","version":"8.0.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"disqus","storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}};
  </script>

  <meta name="description" content="虽然Vue是MVVM框架，但是总有一些场景需要操作真实DOM">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue3中ref模板引用的理解与实践">
<meta property="og:url" content="https://gitee.com/lianghuilin/murmur.git/vue3_practice/Vue3%E4%B8%ADref%E6%A8%A1%E6%9D%BF%E5%BC%95%E7%94%A8%E7%9A%84%E7%90%86%E8%A7%A3%E4%B8%8E%E5%AE%9E%E8%B7%B5/index.html">
<meta property="og:site_name" content="汇话板">
<meta property="og:description" content="虽然Vue是MVVM框架，但是总有一些场景需要操作真实DOM">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/lianghuilin/blog-image-warehouse/raw/master/vue3-ref-demo.gif">
<meta property="article:published_time" content="2021-06-02T17:39:12.000Z">
<meta property="article:modified_time" content="2021-11-28T11:12:12.332Z">
<meta property="article:author" content="William Leung">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/lianghuilin/blog-image-warehouse/raw/master/vue3-ref-demo.gif">


<link rel="canonical" href="https://gitee.com/lianghuilin/murmur.git/vue3_practice/Vue3%E4%B8%ADref%E6%A8%A1%E6%9D%BF%E5%BC%95%E7%94%A8%E7%9A%84%E7%90%86%E8%A7%A3%E4%B8%8E%E5%AE%9E%E8%B7%B5/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Vue3中ref模板引用的理解与实践 | 汇话板</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?a49081c570a782a242cdf6e19e1a584d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/murmur/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">汇话板</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">设定目标，放慢步调，用温和的力量自我改革</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/murmur/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/murmur/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <section class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%AE%A4%E8%AF%86ref%E5%BC%95%E7%94%A8"><span class="nav-number">1.</span> <span class="nav-text">认识ref引用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E5%8F%A5%E8%AF%9D%E7%AE%80%E5%8D%95%E4%BB%8B%E7%BB%8Dref%E6%98%AF%E4%B8%AA%E4%BB%80%E4%B9%88%E9%AC%BC"><span class="nav-number">1.1.</span> <span class="nav-text">3句话简单介绍ref是个什么鬼</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Vue2-x%E4%B8%8EVue3-x%E4%BD%BF%E7%94%A8ref%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="nav-number">1.2.</span> <span class="nav-text">Vue2.x与Vue3.x使用ref的区别</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ref%E6%A8%A1%E6%9D%BF%E5%BC%95%E7%94%A8%E7%9A%84%E6%A1%88%E4%BE%8B%E5%AE%9E%E8%B7%B5"><span class="nav-number">2.</span> <span class="nav-text">ref模板引用的案例实践</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0%E6%95%88%E6%9E%9C"><span class="nav-number">2.1.</span> <span class="nav-text">实现效果</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%BB%E8%A6%81%E6%80%9D%E8%B7%AF"><span class="nav-number">2.2.</span> <span class="nav-text">主要思路</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="nav-number">3.</span> <span class="nav-text">参考资料</span></a></li></ol></div>
        </section>
        <!--/noindex-->

        <section class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">William Leung</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/murmur/archives">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/murmur/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/murmur/tags/">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </section>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">
      

      

  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lianghuilin/murmur.git/vue3_practice/Vue3%E4%B8%ADref%E6%A8%A1%E6%9D%BF%E5%BC%95%E7%94%A8%E7%9A%84%E7%90%86%E8%A7%A3%E4%B8%8E%E5%AE%9E%E8%B7%B5/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/murmur/images/avatar.gif">
      <meta itemprop="name" content="William Leung">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="汇话板">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Vue3中ref模板引用的理解与实践
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-06-03 01:39:12" itemprop="dateCreated datePublished" datetime="2021-06-03T01:39:12+08:00">2021-06-03</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-11-28 19:12:12" itemprop="dateModified" datetime="2021-11-28T19:12:12+08:00">2021-11-28</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/murmur/categories/Vue3%E9%87%87%E5%9D%91%E5%AE%9E%E8%B7%B5/" itemprop="url" rel="index"><span itemprop="name">Vue3采坑实践</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>5.5k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>5 分钟</span>
    </span>
</div>

            <div class="post-description">虽然Vue是MVVM框架，但是总有一些场景需要操作真实DOM</div>
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="认识ref引用"><a href="#认识ref引用" class="headerlink" title="认识ref引用"></a>认识ref引用</h2><h3 id="3句话简单介绍ref是个什么鬼"><a href="#3句话简单介绍ref是个什么鬼" class="headerlink" title="3句话简单介绍ref是个什么鬼"></a>3句话简单介绍<code>ref</code>是个什么鬼</h3><ol>
<li><p>地球人都知道，Vue.js模板当中，既可以写Vue组件，也可以写具体的HTML标签。</p>
</li>
<li><p>同时，Vue提供了一个特殊的<code>ref</code>属性来对普通元素或组件建立引用。</p>
 <figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;page&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;img-container&quot;</span>&gt;</span></span><br><span class="line">            <span class="comment">&lt;!-- 普通HTML --&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">ul</span> <span class="attr">ref</span>=<span class="string">&quot;imgListElm&quot;</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">li</span>&gt;</span><span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">&quot;&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- Vue组件 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">van-button</span> <span class="attr">type</span>=<span class="string">&quot;primary&quot;</span> <span class="attr">ref</span>=<span class="string">&quot;imgBtn&quot;</span>&gt;</span>主要按钮<span class="tag">&lt;/<span class="name">van-button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>如果<code>ref</code>定义在HTML标签，那么引用的就是渲染后具体的DOM对象；如果定义在Vue组件上，则引用组件的Vue实例，进而获取Vue实例内的<code>data</code>数据，或者调用<code>methods</code>方法。</p>
</li>
</ol>
<h3 id="Vue2-x与Vue3-x使用ref的区别"><a href="#Vue2-x与Vue3-x使用ref的区别" class="headerlink" title="Vue2.x与Vue3.x使用ref的区别"></a>Vue2.x与Vue3.x使用<code>ref</code>的区别</h3><p>在视图定义了<code>ref</code>引用后，Vue在编译期间就会自动建立绑定关系，把<code>ref</code>引用挂载到Vue组件实例中，我们在<code>&lt;script&gt;</code>代码中就能直接使用了，但Vue2与Vue3的使用是有些许区别的：</p>
<ul>
<li><strong>Vue2.x将定义的所有<code>ref</code>引用，自动归集在<code>this.$refs</code>集合中。</strong></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    <span class="function"><span class="title">mounted</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="comment">// 普通DOM对象</span></span><br><span class="line">        <span class="keyword">let</span> $imgListElm = <span class="built_in">this</span>.$refs.imgListElm;</span><br><span class="line">        <span class="built_in">console</span>.log($imgListElm.children)</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Vue组件对象</span></span><br><span class="line">        <span class="keyword">let</span> imgBtn = <span class="built_in">this</span>.$refs.imgBtn;</span><br><span class="line">        imgBtn.primary = <span class="string">&#x27;warning&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><strong>Vue3.x需要我们手动把<code>ref</code>引用，赋值到变量。</strong></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// composition API风格</span></span><br><span class="line"><span class="comment">// 提前要把用到的接口，都先import进来</span></span><br><span class="line"><span class="keyword">import</span> &#123; ref, onMounted &#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    <span class="function"><span class="title">setup</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 使用ref()响应式API，定义同名的变量接收ref引用</span></span><br><span class="line">        <span class="keyword">const</span> $imgListElm = ref(<span class="literal">null</span>)</span><br><span class="line">        <span class="keyword">const</span> imgBtn = ref(<span class="literal">null</span>)</span><br><span class="line"></span><br><span class="line">        onMounted(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// 普通DOM对象</span></span><br><span class="line">            <span class="built_in">console</span>.log($imgListElm.children)</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Vue组件对象</span></span><br><span class="line">            imgBtn.primary = <span class="string">&#x27;warning&#x27;</span></span><br><span class="line">        &#125;)</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 记得return要把变量都暴露出去</span></span><br><span class="line">        <span class="keyword">return</span> &#123;</span><br><span class="line">            $imgListElm,</span><br><span class="line">            imgBtn</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>除此之外，还 <strong>允许以<code>:ref</code>的方式进行动态的绑定引用。</strong> 当然，不一定非要用<code>ref()</code>来接收，也可以使用<code>reactive()</code>来接收一个键值对的集合，这样的话，我们就可以像当初通过<code>id</code>操作jQuery对象的方式一样，直接获取到具体的DOM对象。</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 动态ref属性的值是一个JS执行函数，就是对引用进行  赋值  --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">li</span> <span class="attr">v-for</span>=<span class="string">&quot;user in list&quot;</span> </span></span><br><span class="line"><span class="tag">    <span class="attr">:ref</span>=<span class="string">&quot;el =&gt; &#123; if (el) userRefMap[&#x27;ref_&#x27; + user.oid] = el &#125;&quot;</span>&gt;</span></span><br><span class="line">        &#123;&#123; user.name &#125;&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">import</span> &#123; reactive, toRefs &#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span></span><br><span class="line"></span><br><span class="line"><span class="javascript">  <span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line"><span class="javascript">    <span class="function"><span class="title">setup</span>(<span class="params"></span>)</span> &#123;</span></span><br><span class="line"><span class="javascript">        <span class="comment">// 响应数据</span></span></span><br><span class="line"><span class="javascript">        <span class="keyword">const</span> state = reactive(&#123;</span></span><br><span class="line"><span class="javascript">            <span class="comment">// ref映射对象</span></span></span><br><span class="line">            userRefMap: &#123;&#125;,</span><br><span class="line"><span class="javascript">            <span class="comment">// user数组</span></span></span><br><span class="line">            list: [</span><br><span class="line">                &#123;</span><br><span class="line">                    oid: 1001,</span><br><span class="line"><span class="javascript">                    name: <span class="string">&#x27;huilin&#x27;</span></span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                    oid: 1002,</span><br><span class="line"><span class="javascript">                    name: <span class="string">&#x27;fafa&#x27;</span></span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                    oid: 1003,</span><br><span class="line"><span class="javascript">                    name: <span class="string">&#x27;qiqi&#x27;</span></span></span><br><span class="line">                &#125;</span><br><span class="line">            ]</span><br><span class="line">        &#125;)</span><br><span class="line"></span><br><span class="line"><span class="javascript">        onMounted(<span class="function">() =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">            <span class="comment">// 输出DOM</span></span></span><br><span class="line"><span class="javascript">            <span class="built_in">console</span>.log(state.userRefMap[<span class="string">&#x27;ref_1001&#x27;</span>])</span></span><br><span class="line">        &#125;)</span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="keyword">return</span> &#123;</span></span><br><span class="line">            ...toRefs(state),</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="ref模板引用的案例实践"><a href="#ref模板引用的案例实践" class="headerlink" title="ref模板引用的案例实践"></a>ref模板引用的案例实践</h2><h3 id="实现效果"><a href="#实现效果" class="headerlink" title="实现效果"></a>实现效果</h3><p>选中菜品后，进度条渐进加载，2秒后完成确认。同时，允许随时取消选中，再重新进行划菜。</p>
<p><img src="https://gitee.com/lianghuilin/blog-image-warehouse/raw/master/vue3-ref-demo.gif"></p>
<h3 id="主要思路"><a href="#主要思路" class="headerlink" title="主要思路"></a>主要思路</h3><ol>
<li>菜品<code>&lt;div class=&quot;dish-item&quot;&gt;</code>下，要有个<code>&lt;div class=&quot;checked-mask&quot;/&gt;</code>遮罩层。通过改变遮罩层的样式<code>style=&quot;width: 100%&quot;</code>，同时设置<code>transition</code>过渡动画，实现渐进加载效果。</li>
<li>click监听事件中，通过<code>ref</code>引用来操作遮罩层DOM对象。</li>
</ol>
<p>这里可能有人会问：为什么不直接设置动态的<code>:id</code>属性，以<code>document.getElementById()</code>来操作DOM？<br>这是因为JS和DOM是彼此不相通的孤岛，每次访问DOM API都要过一次桥，频繁的过桥会有性能损耗，既然Vue提供了ref的方式，我们尽量还是遵循这个游戏规则</p>
<ul>
<li>核心代码</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">v-for</span>=<span class="string">&quot;dish in dishList&quot;</span> </span></span><br><span class="line"><span class="tag">    <span class="attr">:key</span>=<span class="string">&quot;dish.oid&quot;</span> </span></span><br><span class="line"><span class="tag">    <span class="attr">:class</span>=<span class="string">&quot;&#123;checked : dish.submitted != -1&#125;&quot;</span></span></span><br><span class="line"><span class="tag">    @<span class="attr">click</span>=<span class="string">&quot;dishSubmit(dish)&quot;</span> <span class="attr">class</span>=<span class="string">&quot;dish-item&quot;</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 遮罩层 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">:ref</span>=<span class="string">&quot;el =&gt; &#123; if(el) dishElmMap[&#x27;id_&#x27; + dish.oid] = el&#125;&quot;</span> </span></span><br><span class="line"><span class="tag">        <span class="attr">class</span>=<span class="string">&quot;checked-mask&quot;</span> </span></span><br><span class="line"><span class="tag">        <span class="attr">v-show</span>=<span class="string">&quot;dish.submitted != -1&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 2秒后确认的icon --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">van-icon</span> <span class="attr">:style</span>=<span class="string">&quot;&#123;visibility: dish.submitted == 1 ? &#x27;visible&#x27; : &#x27;hidden&#x27;, opacity: dish.submitted == 1 ? 1 : 0&#125;&quot;</span> </span></span><br><span class="line"><span class="tag">        <span class="attr">name</span>=<span class="string">&quot;checked&quot;</span> </span></span><br><span class="line"><span class="tag">        <span class="attr">class</span>=<span class="string">&quot;checked-icon&quot;</span> </span></span><br><span class="line"><span class="tag">        <span class="attr">size</span>=<span class="string">&quot;30&quot;</span> /&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 菜品名称 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">span</span> <span class="attr">class</span>=<span class="string">&quot;name text-ellipsis&quot;</span>&gt;</span>&#123;&#123;dish.name&#125;&#125;<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 客户备注 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">span</span> <span class="attr">class</span>=<span class="string">&quot;tip text-ellipsis&quot;</span> <span class="attr">style</span>=<span class="string">&quot;text-align: right;&quot;</span>&gt;</span>&#123;&#123;dish.remark&#125;&#125;<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; reactive, toRefs, nextTick &#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    name: <span class="string">&#x27;Order&#x27;</span>,</span><br><span class="line">    <span class="function"><span class="title">setup</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="comment">// 响应数据</span></span><br><span class="line">        <span class="keyword">let</span> state = reactive(&#123;</span><br><span class="line">            dishElmMap: &#123;&#125;,</span><br><span class="line">            dishList: [&#123;</span><br><span class="line">                name: <span class="string">&#x27;干贝苦瓜羹&#x27;</span>,</span><br><span class="line">                remark: <span class="string">&#x27;苦瓜熬久一点&#x27;</span>,</span><br><span class="line">                submitted: -<span class="number">1</span>,</span><br><span class="line">                percent: <span class="number">0</span>,</span><br><span class="line">                oid: <span class="number">332312</span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                name: <span class="string">&#x27;周麻婆泡菜鱼&#x27;</span>,</span><br><span class="line">                remark: <span class="literal">null</span>,</span><br><span class="line">                submitted: -<span class="number">1</span>,</span><br><span class="line">                percent: <span class="number">0</span>,</span><br><span class="line">                oid: <span class="number">332313</span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                name: <span class="string">&#x27;酸辣土豆丝&#x27;</span>,</span><br><span class="line">                remark: <span class="string">&#x27;变态辣&#x27;</span>,</span><br><span class="line">                submitted: -<span class="number">1</span>,</span><br><span class="line">                percent: <span class="number">0</span>,</span><br><span class="line">                oid: <span class="number">332314</span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                name: <span class="string">&#x27;蒜蓉粉丝金针菇&#x27;</span>,</span><br><span class="line">                remark: <span class="literal">null</span>,</span><br><span class="line">                submitted: -<span class="number">1</span>,</span><br><span class="line">                percent: <span class="number">0</span>,</span><br><span class="line">                oid: <span class="number">332315</span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                name: <span class="string">&#x27;飘香馋嘴蛙&#x27;</span>,</span><br><span class="line">                remark: <span class="literal">null</span>,</span><br><span class="line">                submitted: -<span class="number">1</span>,</span><br><span class="line">                percent: <span class="number">0</span>,</span><br><span class="line">                oid: <span class="number">332316</span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                name: <span class="string">&#x27;麻婆田鸡王&#x27;</span>,</span><br><span class="line">                remark: <span class="literal">null</span>,</span><br><span class="line">                submitted: -<span class="number">1</span>,</span><br><span class="line">                percent: <span class="number">0</span>,</span><br><span class="line">                oid: <span class="number">332317</span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                name: <span class="string">&#x27;怀旧水煮鱼&#x27;</span>,</span><br><span class="line">                remark: <span class="literal">null</span>,</span><br><span class="line">                submitted: -<span class="number">1</span>,</span><br><span class="line">                percent: <span class="number">0</span>,</span><br><span class="line">                oid: <span class="number">332318</span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                name: <span class="string">&#x27;一品香脆虾&#x27;</span>,</span><br><span class="line">                remark: <span class="literal">null</span>,</span><br><span class="line">                submitted: -<span class="number">1</span>,</span><br><span class="line">                percent: <span class="number">0</span>,</span><br><span class="line">                oid: <span class="number">332319</span></span><br><span class="line">                &#125;</span><br><span class="line">            ]</span><br><span class="line">        &#125;]</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 菜品提交</span></span><br><span class="line">      <span class="keyword">let</span> dishSubmit = <span class="function">(<span class="params">dish</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 获取具体的DOM</span></span><br><span class="line">        <span class="keyword">let</span> elm = state.dishElmMap[<span class="string">&#x27;id_&#x27;</span> + dish.oid]</span><br><span class="line">        </span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> (dish.submitted === -<span class="number">1</span>) &#123;</span><br><span class="line">          <span class="comment">// 要选中时</span></span><br><span class="line"></span><br><span class="line">          <span class="comment">// -1未划菜；0-划菜中；1-已确认划菜</span></span><br><span class="line">          dish.submitted = <span class="number">0</span>    </span><br><span class="line">          <span class="comment">// 设置DOM.style.width = 100%</span></span><br><span class="line">          nextTick(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            dish.animateTimer = <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">              elm.style.width = <span class="string">&#x27;100%&#x27;</span>;</span><br><span class="line">            &#125;,<span class="number">500</span>)</span><br><span class="line">          &#125;)</span><br><span class="line"></span><br><span class="line">          <span class="keyword">if</span>(dish.timer)&#123;</span><br><span class="line">            <span class="built_in">clearTimeout</span>(dish.timer)</span><br><span class="line">            <span class="built_in">clearTimeout</span>(dish.animateTimer)</span><br><span class="line">          &#125;</span><br><span class="line">          <span class="comment">// 3秒后修改状态为已划菜</span></span><br><span class="line">          dish.timer = <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            dish.submitted = <span class="number">1</span></span><br><span class="line">            <span class="built_in">clearTimeout</span>(dish.timer)</span><br><span class="line">            <span class="built_in">clearTimeout</span>(dish.animateTimer)</span><br><span class="line">          &#125;, <span class="number">2000</span>)</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="comment">// 其他情况回退到初始状态</span></span><br><span class="line">          dish.submitted = -<span class="number">1</span></span><br><span class="line">          nextTick(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">              elm.style.width = <span class="string">&#x27;0%&#x27;</span>;</span><br><span class="line">            &#125;,<span class="number">0</span>)</span><br><span class="line">          &#125;)</span><br><span class="line">          <span class="built_in">clearTimeout</span>(dish.timer)</span><br><span class="line">          <span class="built_in">clearTimeout</span>(dish.animateTimer)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h2><ul>
<li><a target="_blank" rel="noopener" href="https://v3.cn.vuejs.org/guide/composition-api-template-refs.html#jsx-%E4%B8%AD%E7%9A%84%E7%94%A8%E6%B3%95">Vue3官方文档-模板引用</a></li>
<li><a target="_blank" rel="noopener" href="https://cn.vuejs.org/v2/api/#ref">Vue2官方文档-特殊attribute——ref</a></li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>William Leung
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://gitee.com/lianghuilin/murmur.git/vue3_practice/Vue3%E4%B8%ADref%E6%A8%A1%E6%9D%BF%E5%BC%95%E7%94%A8%E7%9A%84%E7%90%86%E8%A7%A3%E4%B8%8E%E5%AE%9E%E8%B7%B5/" title="Vue3中ref模板引用的理解与实践">https://gitee.com/lianghuilin/murmur.git/vue3_practice/Vue3中ref模板引用的理解与实践/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/murmur/vue2_explore/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3nextTick/" rel="prev" title="深入理解nextTick">
                  <i class="fa fa-chevron-left"></i> 深入理解nextTick
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/murmur/ecma_script/ES6%20%E8%AF%A6%E8%A7%A3Set%E5%92%8CWeakSet%E9%9B%86%E5%90%88/" rel="next" title="ES6 详解Set和WeakSet集合">
                  ES6 详解Set和WeakSet集合 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






      

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">
      

      

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">William Leung</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">142k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">2:09</span>
  </span>
</div>
<div class="busuanzi-count">
    <span id="busuanzi_container_site_uv">
      本站访客数<span id="busuanzi_value_site_uv"></span>人次
    </span>
    <span id="busuanzi_container_site_pv">
        本站总访问量<span id="busuanzi_value_site_pv"></span>次
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/murmur/js/utils.js"></script><script src="/murmur/js/motion.js"></script><script src="/murmur/js/next-boot.js"></script>

  
















  <script>
    NProgress.configure({
      showSpinner: true
    });
    NProgress.start();
    document.addEventListener('readystatechange', () => {
      if (document.readyState === 'interactive') {
        NProgress.inc(0.8);
      }
      if (document.readyState === 'complete') {
        NProgress.done();
      }
    });
    document.addEventListener('pjax:send', () => {
      NProgress.start();
    });
    document.addEventListener('pjax:success', () => {
      NProgress.done();
    });
  </script>


  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>








  

  

</body>
</html>
